from flask import Flask, request, redirect, g ,render_template
from flask_sqlalchemy import SQLAlchemy

# 将application目录添加到项目路径，解决views里的文件导入models里的模型类时找不到models模块路径的问题
import sys,os
sys.path.append(os.getcwd() + "/application")
# print(sys.path)

app = Flask(__name__)

#从配置文件中settings加载配置
app.config.from_pyfile('settings.py')

# 将app中的数据库配置加载到app中
db = SQLAlchemy(app)



# 蓝图的导入不要放到最前面，否则会产生循环导入的问题
from application.views.index import route_index
from application.views.user.User import route_user
from application.views.account.Account import route_account
from application.views.food import route_food
from application.views.member.Member import route_member
from application.views.finance.Finance import route_finance
from application.views.stat.Stat import route_stat
from application.views.charts import route_chart

# 注册路由
app.register_blueprint(route_index,url_prefix='/')
app.register_blueprint(route_user,url_prefix='/user')
app.register_blueprint(route_account,url_prefix='/account')
app.register_blueprint(route_food,url_prefix="/food")
app.register_blueprint(route_member,url_prefix="/member")
app.register_blueprint(route_finance,url_prefix="/finance")
app.register_blueprint(route_stat,url_prefix="/stat")
app.register_blueprint(route_chart,url_prefix="/chart")
# print(app.url_map)

# 定义拦截器
'''
判断用户是否登录
'''
# application目录已添加到项目路径,直接从子目录加载即可，不然换个目录，User类和视图中的导入不同重新加载，会报错
from models.user.User import User
from Service import UserService,LogService
import re

def check_login():
    cookies = request.cookies

    if app.config['AUTH_COOKIE_NAME'] in cookies:
        auth_cookie = cookies[app.config['AUTH_COOKIE_NAME']]
    else:
        return False

    auth_cookie_split_list = auth_cookie.split("#")
    g.current_user = None
    try:
        user = User.query.filter_by(uid=auth_cookie_split_list[1]).first()
    except:
        return False

    if user is None:
        return False

    # 将登录用户保存到g对象中
    g.current_user = user

    # 日志记录
    LogService.addNormalLog()

    if auth_cookie_split_list[0] != UserService.geneAuthCode(user):
        return False

    return True


@app.before_request
def before_request():
    path = request.path
    ignore_list = app.config["IGNORE_URLS"]
    reg = "%s" % "|".join(ignore_list)

    if re.match(reg,path):
        return

    if not check_login():
        return redirect("/user/login")


# 统一错误处理
from Service import LogService

@app.errorhandler(404)
def error_404(e):
    LogService.addErrorLog(str(e))
    return render_template("/error/error.html")





